繼昨天的實作練習,有相機,會執行以下的程式碼:
let vc = UIImagePickerController()
vc.sourceType = .camera // 相簿
vc.delegate = self
vc.allowsEditing = true
present(vc, animated: true)
到這邊會報錯是正常的,因為沒給它 UIImagePickerControllerDelegate
因此在專案裡用 extension 去寫委任
extension MainVC: UIImagePickerControllerDelegate, UINavigationControllerDelegate{
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
// 顯示 photo
guard let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage else {return}
imageView.image = image
picker.dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: nil)
}
}
附上完整程式碼
import UIKit
class MainVC: UIViewController {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var takePhoto: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.setNavigationBarHidden(true, animated: false) // 隱藏指示條
}
@IBAction func didTapButton(btn: UIButton) {
let vc = UIImagePickerController()
if !UIImagePickerController.isSourceTypeAvailable(.camera) {
let alertController = UIAlertController(title: "ERROR", message: "Device has no camera.", preferredStyle: .alert)
let okAction = UIAlertAction(title: "Alright", style: .default, handler: { (alert: UIAlertAction!) in
})
alertController.addAction(okAction)
self.present(alertController, animated: true, completion: nil)
print("ERROR:沒有相機功能!")
}
else { vc.sourceType = .camera }
vc.delegate = self
present(vc, animated: true)
}
}
extension MainVC: UIImagePickerControllerDelegate, UINavigationControllerDelegate{
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
picker.dismiss(animated: true, completion: nil)
// 顯示 photo
guard let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage else {return}
imageView.image = image
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: nil)
}
}
為了測試和使用相機,您必須使用真正的連接設備,若燒在模擬器,會報錯:Source type 1 not available
這樣就完成從相簿選取照片的實作了!明天會分享從相簿選取照片( 有裁剪照片功能 ),敬請期待!